import 'dart:async';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../dd_core/dd_config.dart';
import '../../../dd_core/dd_hive_dao.dart';
import '../../../dd_core/dd_http.dart';
import '../../../dd_core/dd_other.dart';
import '../../../dd_core/dd_user_service.dart';
import '../../../dd_models/dd_hive_my_style_model.dart';
import '../../../dd_models/dd_oauth_model.dart';
import '../../../r.dart';
import '../../dd_home/controllers/dd_home_second_controller.dart';
import '../../dd_personal_center/pages/dd_coin_shop_page.dart';

class DDPublishSecondController extends GetxController {
  File? image;

  final images = <Uint8List>[].obs;

  final selectedBackground = ''.obs;

  String selectAssetPath = '';

  TextEditingController control1 = TextEditingController();
  FocusNode focusNode1 = FocusNode();

  TextEditingController control2 = TextEditingController();
  FocusNode focusNode2 = FocusNode();

  final picker = ImagePicker();

  final myStyleObs= <String>[].obs;

  void requestPhotosPermission() async {
    Permission permissionName;
    if (Platform.isIOS) {
      permissionName = Permission.photos;
    } else {
      final androidInfo = await DeviceInfoPlugin().androidInfo;
      final sdkInt = androidInfo.version.sdkInt;
      permissionName = sdkInt < 33 ? Permission.storage : Permission.photos;
    }
    PermissionStatus status = await permissionName.status;
    if (status.isDenied) {
      status = await permissionName.request();
      if (status.isPermanentlyDenied || status.isRestricted) {
        EasyLoading.showToast("You have not authorised this permission.");
      } else if (status == PermissionStatus.granted) {
        _takeImageSource(ImageSource.gallery);
      }
    } else if (status.isPermanentlyDenied) {
      EasyLoading.showToast("You have not authorised this permission.");
    } else {
      _takeImageSource(ImageSource.gallery);
    }
  }

  void _takeImageSource(ImageSource source) async {
    try {
      final pickedFile = await picker.pickImage(source: ImageSource.gallery);
      if (pickedFile != null) {
        final Uint8List? bytes = await pickedFile.readAsBytes();
        if (bytes != null) {
          images.add(bytes);
        }
      }
    } catch (e) {}
  }

  Future<void> submit() async {
    addLocaData();
    // EasyLoading.show();
    // if (selectedBackground != 'bg4') {
    //   Map<String, dynamic>? result = await reviewModeConsume(45);
    //   if (result != null && result['code'] == 0) {
    //     addLocaData();
    //     Get.find<DDUserService>().reloadUserInfo();
    //     Get.find<DDUserService>().reloadUserCoins();
    //   } else {
    //     EasyLoading.dismiss();
    //     EasyLoading.showToast("fail");
    //   }
    // } else if (selectedBackground == 'bg4') {
    //   addLocaData();
    // }
  }

  Future<void> reviewModeConsumeAPi(
      BuildContext context, String bg, String assetPath) async {
    Map<String, dynamic>? result = await reviewModeConsume(48);
    if (result != null && result['code'] == 0) {
      await DDHiveDao.addMyBg(bg: bg);
      Get.find<DDUserService>().reloadUserInfo();
      Get.find<DDUserService>().reloadUserCoins();
      showPrivacyDialog2(context, bg, assetPath);
      selectedBackground.value = bg;
      selectAssetPath = assetPath;
      selectedBackground.refresh();
      getStyleBg();
    } else {
      EasyLoading.dismiss();
      EasyLoading.showToast("fail");
    }
  }

  Future<void> getStyleBg() async {
    List<HiveMyStyleModel>? result = await DDHiveDao.getMyBgList();
    if (result != null && result.length > 0) {
      myStyleObs.value = result[0].myStyle;
      myStyleObs.refresh();
    }
  }

  Future<void> checkMyBg(
    BuildContext context,
    String bg,
    String assetPath,
  ) async {

    if(bg == "bg4"){
      selectedBackground.value = bg;
      selectAssetPath = assetPath;
      return;
    }

    List<HiveMyStyleModel>? result = await DDHiveDao.getMyBgList();
    if (result != null && result.length > 0) {
      bool contains = result[0].myStyle.contains(bg);
      if (contains) {
        selectedBackground.value = bg;
        selectAssetPath = assetPath;
      } else {
        showPrivacyDialog1(context, bg, assetPath);
      }
    } else {
      showPrivacyDialog1(context, bg, assetPath);
    }
  }

  Future<void> checkMyAvailableCoins(
    BuildContext context,
    String bg,
    String assetPath,
  ) async {

    final availableCoins = Get.find<DDUserService>().availableCoins;
    if (availableCoins.value >= 48) {
      reviewModeConsumeAPi(context, bg, assetPath);
    } else {
      showPrivacyDialog3(context, bg, assetPath);
    }
  }

  Future<void> addLocaData() async {
    String author = "Z";
    String followedCount = randomNumber().toString();
    int artworkCount = 0;
    String tags = "";
    DDOauthModel user = Get.find<DDUserService>().authModel;
    String title = control1.text;
    String description = control2.text;
    List<Uint8List>? allImageData = List<Uint8List>.from(images);
    print(selectAssetPath);
    await DDHiveDao.addFencing(
      user.userinfo?.userId ?? '',
      user.userinfo?.userId ?? '',
      user.userinfo?.nickname ?? '',
      user.userinfo?.avatarUrl ?? '',
      author,
      followedCount,
      artworkCount,
      tags,
      title,
      description,
      null,
      null,
      null,
      count: 100,
      allImageData: allImageData,
      myPublish: true,
      bg: selectAssetPath,
    );
    if (Get.isRegistered<DDHomeSecondController>()) {
      Get.find<DDHomeSecondController>().getList();
    }
    control1.text = '';
    control2.text = '';
    images.clear();
    EasyLoading.dismiss();
    EasyLoading.showToast("success");
    navigator?.pop();
  }

  @override
  onInit() {
    super.onInit();
    selectedBackground.value = 'bg4';
    selectAssetPath = R.assetsImagesPublish9;
    getStyleBg();
  }

  @override
  void onClose() {
    control1.dispose();
    control2.dispose();
    focusNode1.dispose();
    focusNode2.dispose();
    images.close();
    selectedBackground.close();
    myStyleObs.close();
    super.onClose();
  }

  void showPrivacyDialog1(
    BuildContext context,
    String bg,
    String assetPath,
  ) {
    Get.dialog(
      barrierDismissible: false,
      Center(
        child: Container(
          decoration: BoxDecoration(
            color: const Color(0xFFD2E8FF),
            borderRadius: BorderRadius.circular(16.0),
          ),
          width: Get.width - 60,
          child:
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(
                height: 24,
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: const Text(
                  'Do you want to buy this skin?',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 24,
                    letterSpacing: 0.0,
                  ),
                ),
              ),
              const SizedBox(
                height: 61,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    GestureDetector(
                      onTap: () async {
                        navigator?.pop();
                        checkMyAvailableCoins(context, bg, assetPath);
                      },
                      child: Container(
                        width: 104,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Color(0xFF53BFD7),
                          border: Border.all(
                            color: Color(0xFF4C5961),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black,
                              spreadRadius: 1,
                              blurRadius: 0,
                              offset: Offset(1, 1),
                            ),
                          ],
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Yes',
                            style: TextStyle(
                                fontFamily: 'Readex Pro',
                                color: Color(0xFFFFFFFF),
                                fontSize: 14,
                                fontWeight: FontWeight.w800),
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        navigator?.pop();
                      },
                      child: Container(
                        width: 104,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Color(0xFFCCCCCC),
                          border: Border.all(
                            color: Color(0xFF4C5961),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black,
                              spreadRadius: 1,
                              blurRadius: 0,
                              offset: Offset(1, 1),
                            ),
                          ],
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'No',
                            style: TextStyle(
                                fontFamily: 'Readex Pro',
                                color: Color(0xFFFFFFFF),
                                fontSize: 14,
                                fontWeight: FontWeight.w800),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              const SizedBox(
                height: 32,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void showPrivacyDialog2(
    BuildContext context,
    String bg,
    String assetPath,
  ) {
    Get.dialog(
      barrierDismissible: false,
      Center(
        child: Container(
          decoration: BoxDecoration(
            color: const Color(0xFFD2E8FF),
            borderRadius: BorderRadius.circular(16.0),
          ),
          width: Get.width - 60,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(
                height: 24,
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: const Text(
                  'Congratulations on getting this skin',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 24,
                    letterSpacing: 0.0,
                  ),
                ),
              ),
              const SizedBox(
                height: 61,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () async {
                        navigator?.pop();
                      },
                      child: Container(
                        width: 163,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Color(0xFF53BFD7),
                          border: Border.all(
                            color: Color(0xFF4C5961),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black,
                              spreadRadius: 1,
                              blurRadius: 0,
                              offset: Offset(1, 1),
                            ),
                          ],
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'OK',
                            style: TextStyle(
                                color: Color(0xffFFFFFF),
                                fontSize: 14,
                                letterSpacing: 0,
                                fontWeight: FontWeight.w800),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(
                height: 32,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void showPrivacyDialog3(
    BuildContext context,
    String bg,
    String assetPath,
  ) {
    Get.dialog(
      barrierDismissible: false,
      Center(
        child: Container(
          decoration: BoxDecoration(
            color: const Color(0xFFD2E8FF),
            borderRadius: BorderRadius.circular(16.0),
          ),
          width: Get.width - 60,
          child:

          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(
                height: 24,
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: const Text(
                  'Do you want to recharge?',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 24,
                    letterSpacing: 0.0,
                  ),
                ),
              ),
              const SizedBox(
                height: 61,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    GestureDetector(
                      onTap: () async {
                        navigator?.pop();
                        DDRoutesConfig.push(DDCoinShopPage(),
                            routeName: "/doinShopPage");
                      },
                      child: Container(
                        width: 104,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Color(0xFF53BFD7),
                          border: Border.all(
                            color: Color(0xFF4C5961),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black,
                              spreadRadius: 1,
                              blurRadius: 0,
                              offset: Offset(1, 1),
                            ),
                          ],
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Yes',
                            style: TextStyle(
                                fontFamily: 'Readex Pro',
                                color: Color(0xFFFFFFFF),
                                fontSize: 14,
                                fontWeight: FontWeight.w800),
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        navigator?.pop();
                      },
                      child: Container(
                        width: 104,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Color(0xFFCCCCCC),
                          border: Border.all(
                            color: Color(0xFF4C5961),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black,
                              spreadRadius: 1,
                              blurRadius: 0,
                              offset: Offset(1, 1),
                            ),
                          ],
                        ),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'No',
                            style: TextStyle(
                                fontFamily: 'Readex Pro',
                                color: Color(0xFFFFFFFF),
                                fontSize: 14,
                                fontWeight: FontWeight.w800),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              const SizedBox(
                height: 32,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
